﻿using Abp.AspNetCore.Mvc.Authorization;
using Choucius.Boilerplate9.Authorization;
using Choucius.Boilerplate9.Configuration;
using Choucius.Boilerplate9.Controllers;
using Choucius.Boilerplate9.PlasticContainers;
using Choucius.Boilerplate9.T4000;
using Choucius.Boilerplate9.Web.Models.T4000Printers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;

namespace Choucius.Boilerplate9.Web.Controllers
{
    [AbpMvcAuthorize(PermissionNames.Pages_Roles)]
    public class T4000PrintersController : Boilerplate9ControllerBase
    {
        //private readonly IWebHostEnvironment _env;
        private readonly IConfigurationRoot _appConfiguration;
        private readonly IT4000AppService _t4000AppService;
        private readonly IPlasticContainerAppService _plasticContainerAppService;

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="env"></param>
        /// <param name="t4000AppService"></param>
        /// <param name="plasticContainerAppService"></param>
        public T4000PrintersController(IWebHostEnvironment env, IT4000AppService t4000AppService, IPlasticContainerAppService plasticContainerAppService)
        {
            //_env = env;
            _appConfiguration = env.GetAppConfiguration();
            _t4000AppService = t4000AppService;
            _plasticContainerAppService = plasticContainerAppService;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ActionName("PrintPost")]
        public ActionResult PrintPost(T4000PrinterViewModel model)
        {
            model.TagSuffix = _plasticContainerAppService.GetMaxValueByRfidAsync(model.TagPrefix).Result;

            string ip = _appConfiguration.GetSection("T4000PrinterSettings:IP").Value;
            int port = Convert.ToInt32(_appConfiguration.GetSection("T4000PrinterSettings:Port").Value);
            for (int i = 0; i < model.TagCount; i++)
            {
                int number = model.TagSuffix + i;
                string formattedNumber = number.ToString("D8"); // 将数字格式化为至少6位的十进制数，不足部分用0填充
                string data = model.TagPrefix + formattedNumber;
                _t4000AppService.PrintAndSaveAsync(ip, port, data);
            }
            //return RedirectToAction("AnotherAction");
            return View("Printing");
        }
    }
}
